<?php

namespace app\admin\controller\financing;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Env;
use function fast\e;

/**
 * 诊疗收费
 *
 * @icon fa fa-user
 */
class Accepts extends Backend
{


    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        //$this->model = new \app\admin\model\Registration;
        $this->model = new \app\admin\model\Accepts;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["users"=>['id','name'],"medic"=>['id','name'],"info"=>['id','name']])
                //->with(["info"=>['id','name','sex','birthday']])
                ->with([
                    'info' => function ($query) {
                        $query->withField('id,name,sex,birthday');
                    }
                ])
                ->where($where)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $list->items()[$k]->age = countage($v->info['birthday']);
                    $list->items()[$k]->receivable = number_format($v->count_cost+$v->other_cost-$v->vip_discounts-$v->iscounts_cost-$v->vip_deduction+($v->new_price),2,'.','');
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $info = Db::table('fa_info')
            ->alias('a')
            ->field('a.*,b.level,b.vip')
            ->join('fa_users b','a.user_id=b.id','left')
            ->where('a.id',$row->info_id)
            ->find();

        //诊疗单
        $diagnosiss = Db::table('fa_diagnosiss')
            ->where('order_id',$row->id)
            ->select();

        //药品单
        $drug = Db::table('fa_drug')
            ->where('order_id',$row->id)
            ->select();

        //会员服务单
        $vip = Db::table('fa_serve')
            ->where('order_id',$row->id)
            ->select();

        //体检项目
        $health = Db::table('fa_health_log')
            ->where('order_id',$row->id)
            ->select();

        if (!empty($info)){
            $info['age'] = countage($info['birthday']);
            $level_name = Db::table('fa_vip_level')
                ->where('level',$info['level'])
                ->find();
            if (!empty($level_name)){
                $info['level_name'] = $level_name['level_name'];
            }else{
                $info['level_name'] = '';
            }

            $card_arr = Db::table('fa_vip_card')
                ->where('id',$info['vip'])
                ->find();

            if (!empty($card_arr)){
                $info['level_name'] = $level_name['level_name'].'('.$card_arr['name'].')';
            }

        }


        //1代表转账，2代表现金，3代表pos机，4代表支付宝，5代表微信，6代表储值卡，7代表积分
        switch ($row->pay){
            case 1:
                $row->pay = '转账';
                break;
            case 2:
                $row->pay = '现金';
                break;
            case 3:
                $row->pay = 'pos机';
                break;
            case 4:
                $row->pay = '支付宝';
                break;
            case 5:
                $row->pay = '微信';
                break;
            case 6:
                $row->pay = '储值卡';
                break;
            case 7:
                $row->pay = '积分';
                break;
            default:
                $row->pay = '无';
                break;
        }

        $row->receivable = number_format($row->count_cost+$row->other_cost-$row->vip_discounts-$row->iscounts_cost-$row->vip_deduction+($row->new_price),2,'.','');

        if ($row->on_credit == 2){
            $row->on_account = '0.00';
        }

        $row->is_custom = 0;
        if (!empty($row->new_str)){
            //$row->new_str = $row->new_str.':'.$row->new_price;
            $row->is_custom = 1;
        }

        $this->view->assign("row", $row);
        $this->view->assign("info", $info);
        $this->view->assign("diagnosiss", $diagnosiss);
        $this->view->assign("drug", $drug);
        $this->view->assign("vip", $vip);
        $this->view->assign("health", $health);
        return $this->view->fetch();
    }

    public function for(){
        $id = request()->param('id');

        $data = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->find();

        if ($data['confirmed'] == 0){
            $this->error('请护士先确认耗材');
        }

        $users_arr = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.info_id,b.user_id,c.level,c.vip')
            ->join('fa_info b','a.info_id=b.id')
            ->join('fa_users c','b.user_id=c.id')
            ->where('a.id',$id)
            ->find();


        //会员服务单
        $vip = Db::table('fa_serve')
            ->where('order_id',$id)
            ->select();

        $new_arr = [];
        $total = 0;
        if (!empty($vip)){
            if (!empty($users_arr)){
                if ($users_arr['level'] != 1){
                    $log = Db::table('fa_vip_relation')
                        ->where('level_id',$users_arr['level'])
                        ->select();


                    foreach ($vip as $k=>$v){
                        foreach ($log as $kk=>$vv){
                            if ($v['serve_id'] == $vv['serve_id']){
                                $total += $v['total'];
                                $vip[$k]['status'] = $vv['status'];
                                if ($vv['status'] != 0){
                                    $deduction_count = Db::table('fa_deduction')
                                        ->field('id,count')
                                        ->where(['user_id'=>$users_arr['user_id'],'serve_id'=>$vv['serve_id']])
                                        ->find();

                                    if (empty($deduction_count)){
                                        $deduction = 0;
                                    }else{
                                        $deduction = $deduction_count['count'];
                                    }

                                    if ($vv['status'] == 1){
                                        if ($deduction < 1){
                                            unset($vip[$k]);
                                        }
                                    }elseif ($vv['status'] == 2){
                                        if ($deduction < 1){
                                            unset($vip[$k]);
                                        }
                                    }elseif ($vv['status'] == 3){
                                        if ($deduction < 2){
                                            unset($vip[$k]);
                                        }
                                    }elseif ($vv['status'] == 4){
                                        if ($deduction < 3){
                                            unset($vip[$k]);
                                        }
                                    }else{
                                        $this->error('数据错误');
                                    }

                                }

                            }
                        }
                    }
                }else{
                    $vip = [];
                    $vips = [];
                }

                $vip = array_merge($vip);
            }
        }

        $for = [];
        if (!empty($data['str'])){
            $for = explode(',',$data['str']);
        }

        if (!empty($data['new_str'])){
            $hi = 1;
        }else{
            $hi = 2;
        }


        $this->view->assign("vip", $vip);
        $this->view->assign("total", $total);
        $this->view->assign("row", $data);
        $this->view->assign("for", $for);
        $this->view->assign("hi", $hi);
        return $this->view->fetch();
    }

    public function fors(){
        $arr = request()->param();


        if (request()->isPost()){
            if ($arr['other_cost'] == ""){
                $this->error('第三方服务费不能为空');
            }

            if ($arr['other_cost'] < 0){
                $this->error('第三方服务费不能小于0');
            }

            if (!empty($arr['is_custom'])){
                if (empty($arr['custom_name'])){
                    $this->error('自定义名称不能为空');
                }

                if (empty($arr['custom_price'])){
                    $this->error('自定义价格不能为空');
                }

                if (!is_numeric($arr['custom_price'])){
                    $this->error('自定义价格不是数字');
                }


            }
//
//            if ($arr['reality_cost'] <= 0){
//                $this->error('实收金额不能为空');
//            }

            $this->success('成功');
        }else{

            $data = Db::table('fa_diagnosis_order')
                ->where('id',$arr['id'])
                ->find();

            $users_arr = Db::table('fa_diagnosis_order')
                ->alias('a')
                ->field('a.info_id,b.user_id,c.level,c.vip')
                ->join('fa_info b','a.info_id=b.id')
                ->join('fa_users c','b.user_id=c.id')
                ->where('a.id',$arr['id'])
                ->find();


            //var_dump($arr['is_custom']);die();
            //$data['pay'] = $arr['pay'];
            $data['is_custom'] = $arr['is_custom'];
            if ($arr['is_custom'] == 1){
                $data['custom_name'] = $arr['custom_name'];
                $data['custom_price'] = number_format($arr['custom_price'],2,'.','');
            }else{
                $data['custom_name'] = '';
                $data['custom_price'] = 0;
                $data['is_custom'] = 0;
            }


            $data['vip_id'] = $arr['vip_id'];
            $data['is_types'] = $arr['is_types'];
            $data['check_code'] = $arr['check_code'];//审批单号
            $data['type'] = $arr['type'];//审批类型
            $data['other_cost'] = $arr['other_cost'];//第三方服务费
            $data['vip_deduction'] = $arr['vip_deduction'];//会员抵扣服务金额

            //$data['reality_cost'] = number_format($arr['reality_cost'],2,'.','');
            //申请优惠金额
            $data['iscounts_cost'] = empty($arr['iscounts_cost']) ?'0.00':number_format($arr['iscounts_cost'],2,'.','');

            $receivable = number_format($data['count_cost']+$arr['other_cost']-$data['iscounts_cost']-$data['vip_deduction']+($data['custom_price']),2,'.','');

            if ($users_arr['vip'] != 0){
                $vip_card = Db::table('fa_vip_card')
                    ->where('id',$users_arr['vip'])
                    ->find();

                $data['vip_discounts'] = number_format($vip_card['discount']/100*$receivable,2,'.','');//会员优惠金额

            }else{
                $data['vip_discounts'] = '0.00';//会员优惠金额
            }



            //应收金额
            $data['receivable'] = number_format($receivable-$data['vip_discounts'],2,'.','');




//            if ($data['reality_cost'] < $data['receivable']){
//                $data['on_account'] = number_format($data['receivable']-$arr['reality_cost'],2,'.','');
//            }else{
//                $data['on_account'] = '0.00';
//            }

        }

        $this->view->assign("row", $data);
        return $this->view->fetch();



    }

    public function edits(){
        $row = $this->request->post("row/a", [], 'trim');
        if ($row['reality_cost'] < 0){
            $this->error('实收金额不能小于等于0');
        }

        if ($row['reality_cost'] > $row['receivable']){
            $this->error('实收金额不能大于应收金额');
        }

        if ($row['on_account'] == 0){
            $on_credit = 0;
            $status = 2;
        }else{
            $on_credit = 1;
            $status = 1;
        }

        $order_arr = Db::table('fa_diagnosis_order')
            ->where('id',$row['id'])
            ->find();

        $users_arr = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.info_id,b.user_id,c.level,c.vip,c.money,c.big_id')
            ->join('fa_info b','a.info_id=b.id')
            ->join('fa_users c','b.user_id=c.id')
            ->where('a.id',$row['id'])
            ->find();

        if ($order_arr['confirmed'] == 0){
            $this->error('请护士先确认耗材');
        }


        if ($order_arr['is_signature'] == 0){
            $update = Db::table('fa_diagnosis_order')
                ->where('id',$row['id'])
                ->update([
                    'other_cost' => $row['other_cost'],
                    'vip_discounts' => $row['vip_discounts'],
                    'iscounts_cost' => $row['iscounts_cost'],
                    'check_code' => $row['check_code'],
                    'update_time' => time(),
                    'vip_deduction' => $row['vip_deduction'],
                    'new_str' => $row['custom_name'],
                    'new_price' => $row['new_price'],
                    'is_type' => $row['type'],
                    'is_types' => $row['is_types'],
                    'str' => $row['vip_id'],
                ]);

            if ($update !== false){
                $this->success('成功');
            }else{
                $this->error('失败');
            }

            die();
        }

        //开启事务
        Db::startTrans();
        if ($row['pay'] == 6){
            $pays = $users_arr['money'] - $row['reality_cost'];
            if ($pays < 0){
                //事务回滚
                Db::rollback();
                $this->error('储值卡余额不足');
            }

            $dec = Db::table('fa_users')
                ->where('id',$users_arr['user_id'])
                ->setDec('money',$row['reality_cost']);

            $log = Db::table('fa_card_log')
                ->insertGetId([
                    'user_id' => $users_arr['user_id'],
                    'money' => $row['reality_cost'],
                    'create_time' => time(),
                    'info_id' => $order_arr['info_id'],
                    'type' => 2,
                ]);
        }else{
            $dec = 1;
            $log = 1;
        }

        $big_id = 0;
        if ($row['pay'] == 7){
            if ($row['reality_cost'] < $row['receivable']){
                $this->error('积分付款实收金额不能小于应收金额');
            }

            $pid_arr = Db::table('fa_users')
                ->where('id',$users_arr['user_id'])
                ->find();

            $integral =  floor($row['reality_cost']/10);

            if (empty($pid_arr)){
                //事务回滚
                Db::rollback();
                $this->error('该账户数据为空');
            }

            $pays = $pid_arr['integral'] - $row['reality_cost'];
            if ($pays < 0){
                //事务回滚
                Db::rollback();
                $this->error('积分不足');
            }

            $decs = Db::table('fa_users')
                ->where('id',$users_arr['user_id'])
                ->setDec('integral',$row['reality_cost']);

            $logs = Db::table('fa_integral_log')
                ->insertGetId([
                    'user_id' => $users_arr['user_id'],
                    'info_id' => $users_arr['info_id'],
                    'integral' => $row['reality_cost'],
                    'create_time' => time(),
                    'type' => 1,
                    'way' => 1,
                ]);

            //加积分
            if (!empty($pid_arr['invite'])){
                $decss = Db::table('fa_users')
                    ->where('id',$pid_arr['invite'])
                    ->setInc('integral',$integral);

                $logss = Db::table('fa_integral_log')
                    ->insertGetId([
                        'user_id' => $pid_arr['invite'],
                        'info_id' => $users_arr['info_id'],
                        'integral' => $integral,
                        'create_time' => time(),
                        'type' => 2,
                        'way' => 1,
                    ]);
            }else{
                $decss = 1;
                $logss = 1;
            }

        }else{
            $decs = 1;
            $logs = 1;
            $decss = 1;
            $logss = 1;

            $big_id = $users_arr['big_id'];
        }



        if ($users_arr['level'] != 1){
            if (!empty($row['vip_id'])){
                $vip_id = explode(',',$row['vip_id']);

                foreach ($vip_id as $k=>$v){

                    $log_vip = Db::table('fa_vip_relation')
                        ->where(['level_id'=>$users_arr['level'],'serve_id'=>$v])
                        ->find();

                if (!empty($log_vip)){
                    if ($log_vip['status'] == 0){
                        $vip_arr = 1;
                    }else{
                        $vip_arr = Db::table('fa_deduction')
                            ->where(['user_id'=>$users_arr['user_id'],'serve_id'=>$v])
                            ->setDec('count',1);

                        if ($vip_arr == false){
                            //事务回滚
                            Db::rollback();
                            $this->error('扣除会员服务次数失败');
                        }
                    }


                }

            }

            }
        }


        $ts_update = 1;
        if (!empty($row['check_code'])){
            if ($row['type'] == 1){
                $t_update = Db::table('fa_oa_give')
                    ->where('code',$row['check_code'])
                    ->find();

                if (empty($t_update)){
                    //事务回滚
                    Db::rollback();
                    $this->error('审批单号错误');
                }

                $ts_update = Db::table('fa_oa_give')
                    ->where('id',$t_update['id'])
                    ->update([
                        'use' => 1,
                        'update_time' => time(),
                    ]);

            }elseif ($row['type'] == 2){
                $t_update = Db::table('fa_oa_buy')
                    ->where('code',$row['check_code'])
                    ->find();

                if (empty($t_update)){
                    //事务回滚
                    Db::rollback();
                    $this->error('审批单号错误');
                }

                $ts_update = Db::table('fa_oa_buy')
                    ->where('id',$t_update['id'])
                    ->update([
                        'use' => 1,
                        'update_time' => time(),
                    ]);
            }
        }

        $big_update = 1;
        if($big_id != 0){
            $big_arr = Db::table('fa_big')
                ->where('id',$big_id)
                ->find();

            if (!empty($big_arr)){
                $receivable = number_format($order_arr['count_cost']+$order_arr['other_cost']-$order_arr['vip_discounts']-$order_arr['iscounts_cost']-$order_arr['vip_deduction']+($order_arr['new_price']),2,'.','');

                $big_update = Db::table('fa_big')
                    ->where('id',$big_id)
                    ->update([
                        'predict' => $big_arr['predict']+$receivable,
                        'update_time' => time(),
                ]);
            }

        }

        $update = Db::table('fa_diagnosis_order')
            ->where('id',$row['id'])
            ->update([
                'other_cost' => $row['other_cost'],
                'vip_discounts' => $row['vip_discounts'],
                'iscounts_cost' => $row['iscounts_cost'],
                'check_code' => $row['check_code'],
                'reality_cost' => $row['reality_cost'],
                'on_account' => $row['on_account'],
                'on_credit' => $on_credit,
                'pay' => $row['pay'],
                'status' => $status,
                'payee' => $this->auth->nickname,
                'update_time' => time(),
                'vip_deduction' => $row['vip_deduction'],
                'big_id' => $big_id,
                'is_type' => $row['type'],
                'is_types' => $row['is_types'],
                'str' => $row['vip_id'],
                'payment_time' => time(),
            ]);

        if (($big_update !== false) && ($ts_update !== false) && ($update !== false) && ($dec !== false) && ($log !== false) && ($decs !== false) && ($logs !== false) && ($decss !== false) && ($logss !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }

    }

    /**
     * 查询申请表
     *
     */
    public function code(){
        $arr = request()->param();

        //会员服务单
        $vip = Db::table('fa_serve')
            ->where('order_id',$arr['id'])
            ->select();

        $amount = 0;
        if ($arr['type'] == 1){
            $order_arr = Db::table('fa_diagnosis_order')
                ->field('id,info_id')
                ->where('id',$arr['id'])
                ->find();

            $data = Db::table('fa_oa_give')
                ->where('code',$arr['code'])
                ->find();

            if (empty($data)){
                $this->error('申请数据为空');
            }

            if ($data['use'] == 1){
                $this->error('该单号已被使用');
            }

            if ($data['status'] != 1){
                $this->error('申请数据审核未通过');
            }

            if ($data['info_id'] != $order_arr['info_id']){
                $this->error('就诊人数据不一致');
            }

            if ($data['type'] == 1){
                if (empty($vip)){
                    $this->error('会员服务为空');
                }

                $detail = Db::table('fa_oa_services')
                    ->where('oa_id',$data['id'])
                    ->select();

                foreach ($vip as $k=>$v){
                    foreach ($detail as $kk=>$vv){
                        if ($v['serve_id'] == $vv['vip_id']){
                            $amount += $vv['total'];
                        }
                    }
                }
            }elseif ($data['type'] == 2){
                $amount = $data['apply_money'];
            }



        }elseif ($arr['type'] == 2){
            $data = Db::table('fa_oa_buy')
                ->where('code',$arr['code'])
                ->find();

            if (empty($data)){
                $this->error('申请数据为空');
            }

            if ($data['use'] == 1){
                $this->error('该单号已被使用');
            }

            if ($data['status'] != 1){
                $this->error('申请数据审核未通过');
            }

            if (empty($vip)){
                $this->error('会员服务为空');
            }

            $detail = Db::table('fa_oa_service')
                ->where('oa_id',$data['id'])
                ->select();


            foreach ($vip as $k=>$v){
                foreach ($detail as $kk=>$vv){
                    if ($v['serve_id'] == $vv['vip_id']){
                        $amount += $vv['total'];
                    }
                }
            }
        }

        $this->success('成功','',$amount);
    }


    /**
     * 退款
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function editp($ids){
        $this->view->assign("row", $ids);
        return $this->view->fetch();
    }



    /**
     * 退款操作
     *
     */
    public function edit_ss(){
        $arr = request()->param();

        if (empty($arr['money'])){
            $this->error('退款金额不能为空');
        }

        if (!is_numeric($arr['money'])){
            $this->error('退款金额不是数字',[]);
        }

        if (floatval($arr['money']) == 0 ){
            $this->error('退款金额不能为0',[]);
        }

        $data = Db::table('fa_diagnosis_order')
            ->field('id,code,on_credit,reality_cost,is_refund,big_id,on_account')
            ->where('id',$arr['id'])
            ->find();

        if (empty($data)){
            $this->error('订单数据为空');
        }

        if ($data['is_refund'] == 1){
            $this->error('已退过款，请勿重复操作');
        }

        if (($data['on_credit'] == 0) || ($data['on_credit'] == 1)){
            if ($data['reality_cost'] < $arr['money']){
                $this->error('退款金额不能大于实收金额');
            }
        }elseif ($data['on_credit'] == 2){
            if (($data['reality_cost']+$data['on_account']) < $arr['money']){
                $this->error('退款金额不能大于实收金额加补缴金额');
            }
        }else{
            $this->error('订单已关闭');
        }


        //开启事务
        Db::startTrans();

        $pan_count = Db::table('fa_treatment')
            ->field('id,finish')
            ->where(['order_id'=>$data['id'],'finish'=>1])
            ->count();

        $pan = Db::table('fa_treatment')
            ->field('id,finish')
            ->where(['order_id'=>$data['id']])
            ->count();

        if ($pan_count == $pan){
            $this->error('订单已完成不能退款');
        }

        $big_arr = Db::table('fa_big')
            ->where('id',$data['big_id'])
            ->find();

        $update_p = 1;
        if (!empty($big_arr)){
            $update_p = Db::table('fa_big')
                ->where('id',$data['big_id'])
                ->update([
                    'predict' => $big_arr['predict']-$arr['money'],
                    'update_time' => time(),
                ]);
        }


        if ($data['on_credit'] != 0){
            $on_credit = 3;
        }else{
            $on_credit = $data['on_credit'];
        }

        $update = Db::table('fa_diagnosis_order')
            ->where('id',$arr['id'])
            ->update([
                'is_refund' => 1,
                'refund' => $arr['money'],
                'refund_time' => time(),
                'on_credit' => $on_credit,
            ]);



        if (($update_p !== false) && ($update !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }


    }


    /**
     * 关闭操作
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     *
     */
    public function close($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {

            if ($row->on_credit == 0){
                $on_credit = 0;
            }else{
                $on_credit = 3;
            }

            $pan_count = Db::table('fa_treatment')
                ->field('id,finish')
                ->where(['order_id'=>$row->id,'finish'=>1])
                ->count();

            $pan = Db::table('fa_treatment')
                ->field('id,finish')
                ->where(['order_id'=>$row->id])
                ->count();

            if ($pan_count == $pan){
                $this->error('订单已完成不能关闭');
            }

            $update = Db::table('fa_diagnosis_order')
                ->where('id',$ids)
                ->update([
                    'status' => 3,
                    'on_credit' => $on_credit,
                    'update_time' => time(),
                ]);

            if ($update !== false){

                $this->success("成功", null, ['id' => $ids]);
            }else{

                $this->error(__('失败'));
            }


        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

}
